package client;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import communication.ClientComm;

public class ClientCommSocket implements ClientComm, Runnable {
	private Thread listener; 
	private ClientModel client;
	private BufferedReader msgFromServer;
	private BufferedWriter msgToServer;
	private boolean exiting;
	private Socket socket ;
	
	public ClientCommSocket(ClientModel cm, String host, int port) throws IOException, UnknownHostException {
		client = cm; exiting = false;
		socket = new Socket(host, port);
		msgFromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		msgToServer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
		listener = new Thread(this, "clientCommLocale");
		listener.start();
	}
	
	@Override
	public void run() {
		while (!exiting) {
			try {
				String msg;
				while (!exiting && (msg = msgFromServer.readLine()) != null) {
					client.arrivaMsgFromServer(msg);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {
			socket.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void msgFromServer(String msg) {}

	@Override
	public void sendRequest(String msg) {
		try {
			msgToServer.write(msg);
			msgToServer.newLine();
			msgToServer.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void clearMessages() {}

	@Override
	public void close() {
		exiting = true;
	}

}
